<template>
  <div class="lb-customer-list">
    <top-nav></top-nav>
    <div class="page-main">
      <el-row class="page-top-operate">
        <!-- <lb-button type='primary' icon='el-icon-plus'>手动添加客户</lb-button> -->
        <lb-button
          type="primary"
          icon="el-icon-plus"
          @click="showAddImport = true"
          >手动添加客户</lb-button
        >
        <lb-button
          type="primary"
          icon="el-icon-plus"
          @click="showAutoImport = true"
          >批量导入客户</lb-button
        >
        <lb-button type="primary" icon="el-icon-download" @click="toExport"
          >导出客户信息</lb-button
        >
      </el-row>

      <el-dialog
        title="手动添加客户"
        :visible.sync="showAddImport"
        width="550px"
        center
      >
        <el-form
          @submit.native.prevent
          :model="addForm"
          :rules="addFormRules"
          ref="addForm"
          label-width="80px"
          class="addForm"
        >
          <el-form-item label="昵称" prop="nickName">
            <el-input
              v-model="addForm.nickName"
              placeholder="请输入昵称"
            ></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input
              v-model="addForm.phone"
              placeholder="请输入电话"
            ></el-input>
          </el-form-item>
          <el-form-item label="头像" prop="avatarUrl">
            <lb-cover
              fileType="image"
              :fileList="addForm.avatarUrl"
              @selectedFiles="getAvatar"
            ></lb-cover>
            <lb-tool-tips>图片建议尺寸: 200 * 200</lb-tool-tips>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showAddImport = false">{{
            $t('action.cancel')
          }}</el-button>
          <el-button type="primary" @click="submitAddFormInfo">{{
            $t('action.add')
          }}</el-button>
        </span>
      </el-dialog>

      <el-dialog
        title="批量导入客户"
        :visible.sync="showAutoImport"
        width="550px"
        center
      >
        <div class="import-content" style="padding-bottom: 20px">
          <p>
            1、首先下载首先下载excel模板；<lb-button
              type="primary"
              @click="importExcelTab"
              >下载excel模板</lb-button
            >
          </p>
          <p>
            2、按模板中的格式编辑好数据（切勿增减调整列，以免引起数据混乱）；
          </p>
          <p>3、选择编辑好的文件，点击上传文件；</p>
          <p>4、等待一段时间，系统提示X条记录上传成功；</p>
        </div>
        <el-form :inline="true" :model="autoForm">
          <el-form-item label="选择文件">
            <el-input
              placeholder="请选择要上传的文件"
              disabled
              v-model="autoForm.file"
              style="width: 280px"
            ></el-input>
            <lb-button
              type="primary"
              @click="clickFileInput"
              style="margin-left: 20px"
              >选择文件</lb-button
            >
            <input
              v-if="showAutoImportInput"
              type="file"
              @change="importf"
              ref="fileInput"
              class="file-input"
              accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
            />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button
            @click="
              () => {
                showAutoImport = false
                showAutoImportInput = false
              }
            "
            >{{ $t('action.cancel') }}</el-button
          >
          <el-button type="primary" @click="submitAutoFormInfo">{{
            $t('action.uploadfile')
          }}</el-button>
        </span>
      </el-dialog>

      <el-row class="page-search-form">
        <el-form :inline="true" :model="searchForm" ref="searchForm">
          <el-form-item label="微信昵称" prop="nickName">
            <el-input
              placeholder="请输入微信昵称"
              v-model="searchForm.nickName"
            ></el-input>
          </el-form-item>
          <el-form-item label="授权类型" prop="empower">
            <el-select
              v-model="searchForm.empower"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in phoneOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="跟进状态" prop="mark">
            <el-select
              v-model="searchForm.mark"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in markOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户状态" prop="intention">
            <el-select
              v-model="searchForm.intention"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in intentionOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="时间查询" prop="range">
            <el-date-picker
              v-model="searchForm.range"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              value-format="timestamp"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <lb-button
              size="medium"
              type="primary"
              icon="el-icon-search"
              style="margin-right: 5px"
              @click="getTableDataList(1)"
              >{{ $t('action.search') }}</lb-button
            >
            <lb-button
              size="medium"
              icon="el-icon-refresh-left"
              style="margin-right: 5px"
              @click="resetForm('searchForm')"
              >{{ $t('action.reset') }}</lb-button
            >
          </el-form-item>
        </el-form>
      </el-row>
      <el-table
        v-loading="loading"
        :data="tableData"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        style="width: 100%"
      >
        <el-table-column prop="nickName" label="微信昵称"> </el-table-column>
        <el-table-column prop="remark_name" label="备注名"> </el-table-column>
        <el-table-column label="微信头像">
          <template slot-scope="scope">
            <lb-image :src="scope.row.avatarUrl"></lb-image>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="授权手机号" width="120">
        </el-table-column>
        <el-table-column prop="birthday" label="生日" width="120">
          <template slot-scope="scope">
            <p v-if="scope.row.birthday">
              {{ scope.row.birthday | handleTime(1) }}
            </p>
          </template>
        </el-table-column>
        <el-table-column label="加入时间" width="120">
          <template slot-scope="scope">
            <p>{{ scope.row.create_time | handleTime(1) }}</p>
            <p>{{ scope.row.create_time | handleTime(2) }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="mark" label="跟进状态"> </el-table-column>
        <el-table-column prop="mark_staff" label="跟进员工"> </el-table-column>
        <el-table-column prop="rate_text" label="意向度(%)"> </el-table-column>
        <el-table-column label="客户状态" width="120">
          <template slot-scope="scope">
            <span>{{
              scope.row.intention_icon === 1 ? '意向客户' : '访客'
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="update_time" label="成交时间" width="120">
          <template slot-scope="scope">
            <div v-if="scope.row.update_time > 0">
              <p>{{ scope.row.update_time | handleTime(1) }}</p>
              <p>{{ scope.row.update_time | handleTime(2) }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="导入客户" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.import ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <div class="table-operate">
              <lb-button
                type="primary"
                size="mini"
                plain
                @click="toShowEdit(scope.row)"
                >编辑资料</lb-button
              >
              <lb-button
                type="danger"
                size="mini"
                plain
                @click="showDialog(scope.row.id)"
                >分配客户</lb-button
              >
              <lb-button
                type="success"
                size="mini"
                plain
                @click="$router.push(`/customer/lookInto?id=${scope.row.id}`)"
                >查看问卷</lb-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <lb-page
        :batch="false"
        :page="searchForm.page"
        :pageSize="searchForm.limit"
        :total="total"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      >
      </lb-page>
    </div>

    <el-dialog
      title="编辑客户资料"
      :visible.sync="showEdit"
      width="550px"
      center
    >
      <el-form
        @submit.native.prevent
        :model="editForm"
        :rules="editFormRules"
        ref="editForm"
        label-width="80px"
        style="width: 500px"
        class="addForm"
      >
        <el-form-item label="昵称" prop="nickName">
          <el-input
            v-model="editForm.nickName"
            placeholder="请输入昵称"
            maxlength="10"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="editForm.phone"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="editForm.gender">
            <el-radio :label="0">未知</el-radio>
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="editForm.birthday"
            :clearable="false"
            type="date"
            placeholder="选择生日"
            value-format="timestamp"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEdit = false">{{
          $t('action.cancel')
        }}</el-button>
        <el-button type="primary" @click="submitEditFormInfo">{{
          $t('action.submit')
        }}</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="分配客户"
      :visible.sync="centerDialogVisible"
      width="750px"
      center
    >
      <div class="dialog-tips">
        分配客户, 需要将客户分配给哪个员工就在哪个员工前打钩, 可以分配给多个员工
      </div>
      <div class="lb-checkbox">
        <el-checkbox-group v-model="checkedStaff" @change="changeCheckBox">
          <el-checkbox
            v-for="(item, index) in staffArr"
            :label="item.id"
            :key="index"
            >{{ item.name }}</el-checkbox
          >
        </el-checkbox-group>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">{{
          $t('action.cancel')
        }}</el-button>
        <el-button type="primary" @click="submitFormInfo">{{
          $t('action.comfirm')
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  reg
} from '@/utils/reg'
import XLSX from 'xlsx'
import pubic from '@/utils/public'
export default {
  data () {
    return {
      addForm: {
        nickName: '',
        phone: '',
        avatarUrl: [{ url: '' }]
      },
      autoForm: {
        file: ''
      },
      addFormRules: {
        // 基本信息验证
        nickName: {
          required: true,
          type: 'string',
          message: '请输入客户昵称',
          trigger: 'blur'
        },
        phone: {
          required: true,
          type: 'string',
          message: '请输入客户电话',
          trigger: 'blur'
        }
        // avatarUrl: {
        //   required: true,
        //   type: 'array',
        //   message: '请上传图片',
        //   trigger: 'change'
        // }
      },

      showAddImport: false,
      showAutoImport: false,
      showAutoImportInput: false,
      customerId: '',
      loading: false,
      centerDialogVisible: false,
      checkedStaff: [],
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      searchForm: {
        empower: 0,
        mark: 0,
        intention: -1,
        nickName: '',
        range: '',
        page: 1,
        limit: 10
      },
      total: 0,
      tableData: [],
      markOptions: [
        {
          label: '全部',
          value: 0
        },
        {
          label: '未跟进',
          value: 3
        },
        {
          label: '跟进中',
          value: 1
        },
        {
          label: '已成交',
          value: 2
        }
      ],
      intentionOptions: [{
        label: '全部',
        value: -1
      },
      {
        label: '访客',
        value: 0
      },
      {
        label: '意向客户',
        value: 1
      }],
      phoneOptions: [
        {
          label: '全部',
          value: 0
        },
        {
          label: '已授权手机号',
          value: 1
        },
        {
          label: '已授权微信昵称/头像',
          value: 2
        }
      ],
      staffArr: [],
      excelData: [],
      showEdit: false,
      editForm: {
        id: '',
        nickName: '',
        phone: '',
        gender: '',
        birthday: ''
      },
      editFormRules: {
        nickName: {
          required: true,
          type: 'string',
          message: '请输入昵称',
          trigger: 'blur'
        },
        phone: {
          required: true,
          type: 'string',
          validator: reg.valiDateTel,
          trigger: 'blur'
        },
        gender: {
          required: true,
          type: 'number',
          message: '请选择性别',
          trigger: 'blur'
        },
        birthday: {
          required: true,
          type: 'number',
          message: '请选择生日',
          trigger: 'blur'
        }
      }
    }
  },
  activated () {
    this.getTableDataList()
    this.getAllStaffs()
  },
  methods: {
    resetForm (name) {
      this.$refs[name].resetFields()
      this.getTableDataList(1)
    },
    changeCheckBox (val) {
      console.log(val)
    },
    /**
     * @method 获取客户列表
     */
    getTableDataList (flag) {
      if (flag) this.searchForm.page = 1
      this.loading = true
      let searchForm = this.$util.pick(this.searchForm, [
        'empower',
        'mark',
        'intention',
        'nickName',
        'page',
        'limit'
      ])
      if (searchForm.intention === -1) {
        delete searchForm.intention
      }
      let { range = '' } = this.searchForm
      if (range) {
        searchForm.start_time = range[0] / 1000
        searchForm.end_time = range[1] / 1000 + 24 * 3600 - 1
      }
      this.$api.getCustomerList(searchForm).then(res => {
        console.log(res)
        this.loading = false
        if (res.code === 200) {
          this.tableData = res.data.data
          this.total = res.data.total
        }
      })
    },
    jumpLookInto (id) {
      this.$router.push(`/customer/lookInto?id=${id}`)
    },
    /**
     * @method: 编辑资料
     * @param {*} item
     */
    toShowEdit (item = {}) {
      item = JSON.parse(JSON.stringify(item))
      item.birthday = item.birthday ? item.birthday * 1000 : ''
      for (let key in this.editForm) {
        this.editForm[key] = item[key]
      }
      this.showEdit = true
    },
    submitEditFormInfo () {
      let param = JSON.parse(JSON.stringify(this.editForm))
      this.$refs['editForm'].validate(valid => {
        if (valid) {
          param.birthday = param.birthday / 1000
          this.$api.customerUpdateUserInfo(param).then((d) => {
            if (d.code === 200) {
              this.$message.success(this.$t('tips.successSave'))
              this.showEdit = false
              this.getTableDataList()
            }
          })
        }
      })
    },
    showDialog (id) {
      this.$api.getStaffsFollowCustomerId({ customer_id: id }).then(res => {
        if (res.code === 200) {
          this.checkedStaff = res.data
          this.customerId = id
          this.centerDialogVisible = true
        }
      })
    },
    getAllStaffs () {
      this.$api.getAllStaffs({ limit: 100000 }).then(res => {
        if (res.code === 200) {
          // console.log(res.data, this.staffArr)
          let list = res.data.data
          list.map((item) => {
            if (item.name.length > 11) {
              item.name = item.name.substring(0, 11) + `...`
            }
          })
          this.staffArr = list
        }
      })
    },
    submitFormInfo () {
      let { customerId, checkedStaff } = this
      if (!checkedStaff.length) {
        this.$message.error('请选择员工后再提交！')
      } else {
        let obj = { customer_id: customerId, staff_id: checkedStaff.join(',') }
        this.$api.distributionCustomer({ data: obj }).then(res => {
          if (res.code === 200) {
            this.$message.success(this.$t('tips.successSub'))
            this.checkedStaff = []
            this.centerDialogVisible = false
            this.getTableDataList()
          }
        })
      }
    },
    handleSizeChange (val) {
      this.searchForm.limit = val
      this.handleCurrentChange(1)
    },
    handleCurrentChange (val) {
      this.searchForm.page = val
      this.getTableDataList()
    },
    async clickFileInput () {
      await this.setInputTrue()
      this.$refs['fileInput'].click()
    },
    setInputTrue () { this.showAutoImportInput = true },
    importf (event) {
      let _this = this
      this.file = event.currentTarget.files[0]
      var rABS = false // 是否将文件读取为二进制字符串
      var file = this.file
      this.autoForm.file = this.file.name
      if (!file) return
      let fileType = file.type
      let fileTypeArr = ['.csv', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel']
      if (fileTypeArr.indexOf(fileType) < 0) {
        this.$message.error('文件类型不正确')
        return
      }
      FileReader.prototype.readAsBinaryString = function (f) {
        var binary = ''
        var rABS = false // 是否将文件读取为二进制字符串
        var workbook // 读取完成的数据
        var reader = new FileReader()
        reader.onprogress = function (e) { // 读取文件的进度
          let total = file.size
          _this.progress = (e.loaded / total) * 100
        }
        reader.onload = function (e) {
          try {
            var bytes = new Uint8Array(reader.result)
            var length = bytes.byteLength
            for (var i = 0; i < length; i++) {
              binary += String.fromCharCode(bytes[i])
            }
            if (rABS) {
              workbook = XLSX.read(btoa(_this.fixdata(binary)), { // 手动转化
                type: 'base64'
              })
            } else {
              workbook = XLSX.read(binary, {
                type: 'binary'
              })
            }
          } catch (e) {
            _this.$message.error('文件类型不正确')
            return
          }
          let importData = []
          for (var sheet in workbook.Sheets) {
            if (workbook.Sheets.hasOwnProperty(sheet)) {
              // let fromTo = workbook.Sheets[sheet]['!ref']
              // console.log(fromTo)
              importData = importData.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]))
            }
          }
          _this.excelData = importData.map(item => {
            return {
              nickName: item['昵称'],
              phone: item['电话'],
              avatarUrl: item['头像链接'] || ''
            }
          })
          console.log(_this.excelData, '===========> this.excelData')
        }
        reader.readAsArrayBuffer(f)
      }

      var reader = new FileReader()
      if (rABS) {
        reader.readAsArrayBuffer(file)
      } else {
        reader.readAsBinaryString(file)
      }
    },
    fixdata (data) { // 文件流转BinaryString
      let o = ''
      let l = 0
      let w = 10240
      for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)))
      o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)))
      return o
    },
    /**
       * @method 获取员工头像
       */
    getAvatar (imgs) {
      this.addForm.avatarUrl = imgs
    },
    /**
     * @method: 手动导入客户
     */
    submitAddFormInfo () {
      let { addForm } = this
      let queryForm = JSON.parse(JSON.stringify(addForm))
      this.$refs['addForm'].validate(valid => {
        if (valid) {
          queryForm.avatarUrl = queryForm.avatarUrl.length > 0 ? queryForm.avatarUrl[0].url : ''
          this.$api.importCustomer({ data: [queryForm] }).then((d) => {
            if (d.code === 200) {
              this.$message.success(this.$t('tips.successSave'))
              this.addForm.nickName = ''
              this.addForm.phone = ''
              let imgs = [{ url: '' }]
              this.getAvatar(imgs)
              this.showAddImport = false
              this.searchForm.page = 1
              this.getTableDataList()
            }
          })
        } else {
          this.$message.error(this.$t('tips.fillValidate'))
        }
      })
    },
    /**
     * @method: 自动导入客户
     */
    submitAutoFormInfo () {
      let { excelData } = this
      this.showAutoImportInput = false
      let queryForm = JSON.parse(JSON.stringify(excelData))
      let length = queryForm.length
      if (length > 0) {
        for (let key in queryForm) {
          let index = key * 1 + 1
          if (!queryForm[key].nickName) {
            this.$message.error(`导入客户 第${index}条数据：请完善客户昵称`)
            return
          } else if (!queryForm[key].phone) {
            this.$message.error(`导入客户 第${index}条数据：请完善客户电话`)
            return
          }
        }
        this.$api.importCustomer({ data: queryForm }).then((d) => {
          if (d.code === 200) {
            this.$message.success(`${length}条记录上传成功`)
            // this.excelData = []
            // this.file = ''
            // this.autoForm.file = ''
            this.showAutoImport = false
            this.searchForm.page = 1
            this.getTableDataList()
          }
        })
      } else {
        this.$message.error(this.$t('tips.chooseFile'))
      }
    },
    /**
       * @method 下载excel模板
       */
    importExcelTab () {
      let url = pubic.getProCurrentHref()
      let keywords = url.indexOf('?') > 0 ? '' : '?'
      let token = sessionStorage.getItem('minitk')
      let dwonlaodUrl = `${url}/customer/admin/getExcelPath${keywords}&token=${token}`
      console.log(dwonlaodUrl, 'dwonlaodUrl')
      window.location.href = dwonlaodUrl
    },
    /**
       * @method 导出客户信息
       */
    toExport () {
      this.downloadLoading = true
      let searchForm = this.$util.pick(this.searchForm, [
        'empower',
        'mark',
        'nickName',
        'page',
        'limit'
      ])
      let range = JSON.parse(JSON.stringify(this.searchForm.range))
      if (range && range.length > 0) {
        searchForm.start_time = range[0] / 1000
        searchForm.end_time = range[1] / 1000 + 24 * 3600 - 1
      } else {
        searchForm.start_time = ''
        searchForm.end_time = ''
      }
      let url = pubic.getProCurrentHref()
      let keywords = url.indexOf('?') > 0 ? '' : '?'
      let flag = url.indexOf('?') > 0
      Object.getOwnPropertyNames(searchForm).forEach((keys, value) => {
        keywords += flag ? `&${keys}=${searchForm[keys]}` : `${keys}=${searchForm[keys]}`
        flag = true
      })
      let token = sessionStorage.getItem('minitk')
      let dwonlaodUrl = `${url}/customer/admin/customerExcel${keywords}&token=${token}`
      window.location.href = dwonlaodUrl
      setTimeout(() => {
        this.downloadLoading = false
      }, 5000)
    }
  },
  filters: {
    handleTime (val, type) {
      let time = type === 1 ? moment(val * 1000).format('YYYY-MM-DD') : type === 2 ? moment(val * 1000).format('HH:mm:ss') : moment(val * 1000).format('YYYY-MM-DD HH:mm:ss')
      return time
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-customer-list {
  .el-select,
  .el-input-number,
  .el-input {
    width: 200px;
  }
  width: 100%;
  .page-main {
    width: 100%;
    .file-input {
      display: none;
    }
  }
}
.dialog-tips {
  background-color: #ecf8ff;
  border-left: 5px solid #50bfff;
  border-radius: 4px;
  padding: 8px 16px;
}
.lb-checkbox {
  max-height: 500px;
  margin-top: 20px;
  overflow-x: hidden;
  .el-checkbox {
    width: 200px;
    margin-bottom: 10px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .el-radio {
    width: 100px;
    margin-bottom: 10px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}

.import-content {
  p {
    color: #333;
    font-size: 14px;
    line-height: 1.5;
    padding-bottom: 10px;
  }
}
.addForm {
  .el-input {
    width: 300px;
  }
}
</style>
